<?php
function ListAllProduct($idP=0,$isNew=false,$isHot=false,$isTypical=false)
{
    global $dbsql,$language;
    ImportClass('json');
    $sql_where  = " from tblproduct where iStatus=1 and cLanguage='$language' ";
    if($idP>0)
    {
        $listidChild = ListChildIdProductCat($idP);
        $sql_where  .= " and iParentId in ($listidChild) ";
    }
    
    if($isNew==true)
    {
        $sql_where  .= " and iNew = 1 ";
    }
    if($isHot==true)
    {
        $sql_where  .= " and iHot = 1 ";
    }
    if($isTypical==true)
    {
        $sql_where  .= " and iTypical = 1 ";
    }
    
    $sql_select = "select count(iId) as count ".$sql_where;
    $result     = $dbsql->query_fetch($sql_select);
    list($lf,$la)= Split_Page($result['count']);
    
    $sql_select = "select * ".$sql_where." order by iOrder limit $lf,$la";
    $rs         = $dbsql->query($sql_select);
    $rows       = $dbsql->num_rows($rs);
    if($rows==0)
    {
        return '<div class="notfound">'.getLang('Not Found Product').'</div>';
    }
    
    return BuildListProduct($rs);
}

function ListChildIdProductCat($idP)
{
    global $dbsql,$language;
    $list       = array($idP);
    $sql_select = "select iId from tblproduct_category where iParentId='$idP' and iStatus=1";
    $rs         = $dbsql->query($sql_select);
    while($result   = $dbsql->fetch_array($rs))
    {
        $list[] = $result['iId'];
    }
    return implode(',',$list);
}

function ListOtherProduct($id,$idP,$limit=4)
{
    global $dbsql,$language;
   
    $sql_select = "select * from tblproduct where iParentId='$idP' and iId!='$id' 
                and cLanguage='$language' order by iOrder limit $limit";
    $rs         = $dbsql->query($sql_select);
    $rows       = $dbsql->num_rows($rs);
    if($rows==0)
    {
        return '<div class="notfound">'.getLang('Not Found Product').'</div>';
    }
    
    return BuildListProduct($rs);
}

function BuildListProduct($rs)
{
    global $dbsql,$show_page;
    
    $linkproductroot= getUrlCatByType('product'); 
    $html       = '<div id="ajaxPage">';
    $html      .= '<table cellpadding="0" cellspacing="0" class="prolist">';
    while($result= $dbsql->fetch_array($rs))
    {
        $imglink= GetIntroImg($result['cImage'],true);
        $link   = GetLinkProduct($result['iParentId'],$result['cUrlString']);
        $property_text  = $result['cDescription'];
        if(strlen(strip_tags($property_text))<10)
        {
            $property_text= '';
            $properties= FJSON::decode($result['cProperty'],true);        
            foreach($properties as $property)
            {
                $property_text.='- '.$property[1].': '.$property[3].'<br>';
            }
        }
        
        $html  .= '<tr><td valign=top width=140>';
        $html  .= '<span class="img"><a href="'.echoLink($link,false).'"><img src="'.($imglink).'" width="100%" border=0></a>';
        $html  .= '<div class="c">'.$result['cCode'].'</div>';
        $html  .= '<div class="pri">'.getPriceClient($result['cPrice']).'</div></span>';
        $html  .= '</td><td valign=top>';
        $html  .= '<a class="ttp" href="'.echoLink($link,false).'">'.$result['cName'].'</a>';
        $html  .= '<span class="prop">'.$property_text.'</span>';
        $html  .= '<div class=" more">';
        $html  .= '<a onclick="addcart('.$result['iId'].')">'.getLang('Add Cart').'</a> | <a href="'.echoLink($link,false).'">'.getLang('Detail').'</a>';
        $html  .= '</div><div class="clear"></div>';
        $html  .= '</td></tr>';
    } 
    $html   .= '</table>';
    $html   .= $show_page;   
    $html   .= '</div>'; 
    return $html;
}


function ListProductCat()
{
    global $dbsql,$language;
    
    $sql_select = "select cName,cUrlString,cImage from tblproduct_category where iStatus=1 and iParentId=0 and iPlace=1 and cLanguage='$language'
                    order by iOrder ";
    return $dbsql->load($sql_select);
}

function BuildNewProduct($limit=6)
{
    global $dbsql,$language;
    
    $sql_select = "select cName,cUrlString,cImage,iParentId from tblproduct 
                    where iStatus=1 and cLanguage='$language' and iNew = 1
                    order by iOrder limit $limit ";
                    
    $rs         = $dbsql->query($sql_select);
    $rows       = $dbsql->num_rows($rs);
    if($rows==0)
    {
        return;
    }
    $html       = '<div class="t">'.getLang('New Product').'</div>';
    $linkproductroot= getUrlCatByType('product'); 
    $i          = 0;
    while($result   = $dbsql->fetch_array($rs))
    {
        $imglink= GetIntroImg($result['cImage']);
        $link   = GetLinkProduct($result['iParentId'],$result['cUrlString']);
        $html .= '<a class="listproduct ';
        if($i%2==0)
        {
            $html .= 'dotr';
        }
        $html .=  '" href="'.echoLink($link,false).'">';
        $html .= '<span class="img"><img src="'.($imglink).'" width="90%" border="0"></span>';
        $html .= '<span class="tp">'.$result['cName'].'</span></a>';
        $i++;
    }
    $html .= '<div class="clear">&nbsp;</div>';
    $html .= '<div class="more">';
    $html .= '&raquo; <a class="more" href="'.echoLink($linkproductroot,false).'/new">'. getLang('View all').'</a>';
    $html .= '</div><div class="clear">&nbsp;</div>';
    return $html;
}

function BuildTypicalProduct($limit=6,$random=false)
{
    global $dbsql,$language;
    
    $sql_select = "select cName,cUrlString,cImage,iParentId from tblproduct 
                    where iStatus=1 and iTypical =1 and cLanguage='$language'
                    order by ";
    if($random==true)
    {
        $sql_select .= " rand() ";
    }else
    {
        $sql_select .= " iOrder ";
    }            
    $sql_select.= " limit $limit ";
    $rs         = $dbsql->query($sql_select);
    $rows       = $dbsql->num_rows($rs);
    if($rows==0)
    {
        return;
    }
    $html       = '<div class="t linetop">'.getLang('Typical Product').'</div>';
    $linkproductroot= getUrlCatByType('product'); 
    $i          = 0;
    while($result   = $dbsql->fetch_array($rs))
    {
        $imglink= GetIntroImg($result['cImage']);
        $link   = GetLinkProduct($result['iParentId'],$result['cUrlString']);
        $html .= '<a class="listproduct ';
        if($i%2==0)
        {
            $html .= 'dotr';
        }
        $html .=  '" href="'.echoLink($link,false).'">';
        $html .= '<span class="img"><img src="'.($imglink).'" width="90%" border="0"></span>';
        $html .= '<span class="tp">'.$result['cName'].'</span></a>';
        $i++;
    }
    $html .= '<div class="clear">&nbsp;</div>';
    $html .= '<div class="more">';
    $html .= '&raquo; <a class="more" href="'.echoLink($linkproductroot,false).'/typical">'. getLang('View all').'</a>';
    $html .= '</div><div class="clear">&nbsp;</div>';
    return $html;
}

function GetLinkProduct($idP,$url)
{
    return getUrlCatByType('product').'/'.getLinkParentProduct($idP).$url.'.htm';
}

function getLinkParentProduct($idP)
{
    global $dbsql,$language,$urlsParentProducts;
    
    if(isset($urlsParentProducts[$idP]))
    {
        return $urlsParentProducts[$idP];
    }
    $sql_select = "select cUrlString,iParentId from tblproduct_category where iId='$idP' and cLanguage='$language'";
    $result     = $dbsql->query_fetch($sql_select);
    if($result==false)
    {
        return;
    }
    if($result['iParentId']>0)
    {
        $urlP   = getLinkParentProduct($result['iParentId']);
    }
    if(!empty($result['cUrlString']))
    {
        $result['cUrlString'].='/';
    }
    
    $urlsParentProducts[$idP]   = $urlP.$result['cUrlString'];
    return $urlsParentProducts[$idP];
}

function LoadProductById($id,$fields=null)
{
global $dbsql;
	$sql_select="select ".(($fields==null)? '*': $fields)." from tblproduct where iId=$id";
	$rs    =$dbsql->query($sql_select);
	$result=$dbsql->fetch_array($rs);
	return $result;
}

function ListCart()
{
    global $dbsql,$language;
    
    $carts      = gpc_getSession(LISTCART_SESSION);   
    if(!is_array($carts))
    {
        return array('count'=>0);
    }
    $count      = 0;
    $msg        = '<table>';
    foreach($carts as $i=>$cart)
    {
        $count++;
        $product    = LoadProductById($cart['id'],'cName,iParentId,cUrlString');
        $link       = GetLinkProduct($product['iParentId'],$product['cUrlString']);
        $msg       .= '<tr><td valign=top>'.$count.'.</td><td>';
        $msg       .= '<a href="'.echoLink($link,false).'">'.$product['cName'].'</a>';
        $msg       .= '</td></tr>';
    }
    $msg       .= '</table>';
    if($count==0)
    {
        $msg    = getLang('Your cart is empty');
    }
    return array('count'=>$count,'msg'=>$msg);
}

function BuildListCart($carts=null,$edit=true)
{
    global $dbsql,$language;
    
    if(!is_array($carts))
    {
        $carts      = gpc_getSession(LISTCART_SESSION);    
    }
       
    if(!is_array($carts) || count($carts)==0)
    {
        return '<div class="notfound">'.getLang('Not found product in cart').'</div>';
    }
    $html       = '<form method="post" action="'.echoAction('updatecart',false).'" onsubmit="return updateCart(this)">';
    $html      .= '<input type="hidden" name="opt" value="update" />';
    $html      .= '<table class="tblcart" width="100%" cellpadding="0" cellspacing="0">';
    $html      .= '<tr>';
    $html      .= '<th>'.getLang('Product Name').'</th>';
    $html      .= '<th width=10% nowrap>'.getLang('Price').'</th>';
    $html      .= '<th  width=10% nowrap>'.getLang('Count').'</th>';
    $html      .= '<th width=10% nowrap>'.getLang('Total price').'</th>';
    if($edit==true)
    {
        $html      .= '<th  width=5% nowrap></th>';    
    }
    
    $html      .= '</tr>';
    $totalprice = 0;
    foreach($carts as $i=>$cart)
    {
        $product    = LoadProductById($cart['id'],'cName,iParentId,cUrlString,cPrice');
        $link       = GetLinkProduct($product['iParentId'],$product['cUrlString']);
        $pricett    = $product['cPrice']*$cart['count'];
        $totalprice+= $pricett;
        $html      .= '<tr id="cart_'.$i.'">';
        $html      .= '<td>'.($i+1).'. <a href="'.echoLink($link,false).'">'.$product['cName'].'</a></td>';
        $html      .= '<td align=right nowrap>'.getPriceClient($product['cPrice']).'</a></td>';
        if($edit==true)
        {
            $html      .= '<td align=right><input name="count_'.$i.'" id="count_'.$i.'" value="'.$cart['count'].'"></td>';
        }else
        {
            $html      .= '<td align=right>'.$cart['count'].'</td>';
        }
        
        $html      .= '<td align=right nowrap>'.getPriceClient($pricett).'</a></td>';
        if($edit==true)
        {
            $html      .= '<td><a onclick="delrow('.$i.')">'.getLang("delete").'</a></td>';
        }        
        $html      .= '</tr>';
    }
    $html      .= '</table>';    
    $html      .= '<div class="totalPrice">'.getLang('Total Price Order').': <span>'.getPriceClient($totalprice).'</span></div>';
    if($edit==true)
    {        
        $html      .= '<input type="submit" id="butsubmit"  class="submit" value="'.getLang('Update').'">';
        $html      .= '<input type="submit" class="submit" onclick="this.form.opt.value=\'del\'" value="'.getLang('Clear').'">';
        $html      .= '<div class="clear"></div>';
    }
        
    $html      .= '</form>';
    return $html;
}

function AddCart()
{
    global $dbsql,$language;
    
    $id         = gpc_getIntPost('id'); 
    $carts      = gpc_getSession(LISTCART_SESSION);      
    $product    = LoadProductById($id);
    if($product==false)
    {
        AjaxTransfer('false',getLang('Not found Product'));
    }
    if(!is_array($carts))
    {
        $carts  = array();
    }
    $hasProduct = false;
    foreach($carts as $i=>$cart)
    {
        if($id==$cart['id'])
        {
            $hasProduct = true;
        }
    }
    if($hasProduct == false)
    {
        $carts[]  = array('id'=>$id,'count'=>1);
    }
    gpc_setSession(LISTCART_SESSION,$carts);
    $cartsmsg    = ListCart();
    AjaxTransfer('ok',array('msg'=>getLang('Add Cart Success'),'count'=>$cartsmsg['count'],'cart'=>$cartsmsg['msg']));
}

function UpdateCart()
{
    global $dbsql,$language,$actPost;
    if($actPost=='del')
    {
        gpc_removeSession(LISTCART_SESSION);
        $carts      = array();
    }else
    {
        $carts      = gpc_getSession(LISTCART_SESSION);
    }
      
    $carts_new  = array();
    if(!is_array($carts))
    {
        $carts  = array();
    }
    
    foreach($carts as $i=>$cart)
    {
        $count  = gpc_getIntPost('count_'.$i);
        if($count==-1)
        {
            continue;
        }else if($count==0)
        {
            $count  = $cart['count'];
        }
        
        $carts_new[] = array('id'=>$cart['id'],'count'=>$count);
    }
    gpc_setSession(LISTCART_SESSION,$carts_new);
    $listcartmsg    = BuildListCart($carts_new);
    if($actPost=='continue')
    {
        $url    = getUrlCatByType('product').'/order';
        Redirect($url);
        exit;
    }
    $cartsmsg    = ListCart();
    AjaxTransfer('ok',array('msg'=>$listcartmsg,'count'=>$cartsmsg['count'],'cart'=>$cartsmsg['msg']));
}

function AddOrder()
{
    global $root_domain,$ip;
    ImportClass('captcha');
    if (PhpCaptcha::Validate($_POST['SpamCode'])==false)
    {
         AjaxTransfer('spam',getLang('Please enter the correct security code!'));
    }
    //Personal Details
	$FullName      = gpc_getStringPost('fullname');
	$Email		   = gpc_getStringPost('Email');	
	$Address       = gpc_getStringPost('Address'); 
	$Phone         = gpc_getStringPost('Phone');
	$Other         = gpc_getStringPost('Other');  
    $listproduct   = BuildListProductCart();
    
    
    if(!isEmail($Email))
    {
        AjaxTransfer('false',getLang('Please enter your email'));
    }
    
    if($listproduct==false)
    {
        AjaxTransfer('false',getLang('Your cart is empty'));
    }
    
    //insert Db:    
    ImportClass('booking');
    
    InsertBooking('product',$ProductId,$FullName,"",$Email,$Phone,$Address,"","","",$Other.'<br>'.$listproduct,0);
    
    $emailconfig  = getConfigEmail('BookingProduct');
    $subject      = $emailconfig->title;
    $message      = $emailconfig->content;
    $email_admin  = $emailconfig->email;   
    
    
    //send mail to admin:  
    $subject_admin= getLang('Order of ').$FullName.'-'.$Email;  
    $message_admin= "<b>Customer info</b>:<br>";
    $message_admin.= "Fullname: ".$FullName.'<br>';
    $message_admin.= "Email: ".$Email.'<br>';
    $message_admin.= "Address: ".$Address.'<br>';
    $message_admin.= "Phone: ".$Phone.'<br>';
    $message_admin.= "Other: ".$Other.'<br><br><br>';
    $message_admin.= "<b>List Product: </b>".$listproduct.'<br>';
    $message_admin.= "<br><br>IP: ".$ip;
    
    send_email($email_admin,"",$subject_admin,$message_admin);
    
    //SEND EMAIL TO CUSTOMER:
    $lists        = array('{SITE}','{NAME}','{EMAIL}','{LISTPRODUCT}');
    $listr        = array($root_domain,$FullName,$Email,$listproduct);
    $subject      = str_replace($lists,$listr,$subject);
    $message      = str_replace($lists,$listr,$message);
    send_email($Email,$FullName,$subject,$message);
    
	
    AjaxTransfer('ok',getLang('Your booking sent Success'));
    
}

function BuildListProductCart()
{
    global $dbsql,$language;
    
    $carts      = gpc_getSession(LISTCART_SESSION);  
    
    if($carts==false || !is_array($carts))
    {
        return false;
    }       
  
    $html       = '<table class="tblcart" width="660" border=1 >';
    $html      .= '<tr>';
    $html      .= '<th>'.getLang('Product Name').'</th>';
    $html      .= '<th width=10% nowrap>'.getLang('Price').'</th>';
    $html      .= '<th  width=10% nowrap>'.getLang('Count').'</th>';
    $html      .= '<th width=10% nowrap>'.getLang('Total price').'</th>';  
    $html      .= '</tr>';
    $totalprice = 0;
    foreach($carts as $i=>$cart)
    {
        $product    = LoadProductById($cart['id'],'cName,iParentId,cUrlString,cPrice');
        $link       = GetLinkProduct($product['iParentId'],$product['cUrlString']);
        $pricett    = $product['cPrice']*$cart['count'];
        $totalprice+= $pricett;
        $html      .= '<tr id="cart_'.$i.'">';
        $html      .= '<td>'.($i+1).'. <a href="'.echoLink($link,false,2).'">'.$product['cName'].'</a></td>';
        $html      .= '<td align=right nowrap>'.getPriceClient($product['cPrice']).'</a></td>';
        $html      .= '<td align=right>'.$cart['count'].'</td>';        
        $html      .= '<td align=right nowrap>'.getPriceClient($pricett).'</a></td>';            
        $html      .= '</tr>';
    }
    $html      .= '</table>';   
    $html      .= '<div class="totalPrice">'.getLang('Total Price Order').': <span>'.getPriceClient($totalprice).'</span></div>'; 
    return $html;
}
?>